<?php
/**
 * 模块管理
 *
 * PHP Version 5.6
 *
 * @author    guanxu <510104561@qq.com>
 * @time      2017/08/11
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Common\ConstantUtil;
use Think\Page;
Class ModulesController extends CommonController {

    /**
     * 栏目选择
     * @return mixed
     */
    public function columnSelect() {
        $id = I("get.id");
        $request = I("");
        if(empty($id)) {
            session("column_select",null);
            A("index")->index();
            exit;
        }
        $admin_modules = session("admin_modules");
        $modules_select = $admin_modules["modules"][$id]["list"];
        $modules_id=  $modules_select[key($modules_select)]["list"][0]["id"];
        session("modules_select",$modules_select);
        session("column_select",$id);
        $result = $this->modules_select($modules_id,$request);
        return $result;

    }

    /**
     * 点击模块
     * @param 
     * @return mixed
     */
    public function select() {

        $id = I("get.id");
        if(empty($id)) $this->error("请选择正确模块！");
        $result = $this->modules_select($id,I(""));
        return $result;
    }

    /**
     * 选择模块请求
     * @param $id
     * @param $request
     * @return mixed
     */
    private function modules_select($id,$request) {

        $url = M("modules")->where(["id"=>$id])->getField("url");
        $url = $this->urlManage($url);
        if(empty($url))   $this->error("请确认URL正确！",U('index/login'));
        $session_modules = session("admin_modules");
        if(!empty($session_modules["function"])) {
            $request_uri = U($url);
            //var_dump($request_uri);
            //var_dump($session_modules["function"]);
            if(!in_array($request_uri,$session_modules["function"])) $this->error("该模块无权限!","/Admin/index/index");
        }
        session("select",$id);
        $next = explode('/',$url);
        A($next[0])->$next[1]();
    }



    /**
     * 模块列表页
     */
    public function index() {
        $select["classify_id"] = I("post.classify");
        $result = [];
        $classify = D("Classify")->getClassify();

        if(!empty($select["classify_id"])) $where = ["classify.id"=>$select["classify_id"]];
        $where["modules.status"] = ConstantUtil::GLOBAL_TRUE;
        import('ORG.Think.Page');
        $user_mobile_code =  M("modules")->join("classify on classify.id  = modules.classify_id")->where($where);
        $user_mobile_code_count = clone $user_mobile_code ;
        $count  = $user_mobile_code_count->count();
        $page   = new Page($count,ConstantUtil::ADMIN_PAGE);
        $show   = $page->show();
        $list   = $user_mobile_code->limit($page->firstRow.','.$page->listRows)->field("modules.* ,classify.name as classify_name")->order("id desc")->select();

        //$modules = ->field("modules.* ,classify.name as classify_name");
        //if(!empty($select["classify_id"])) $modules->where(["classify.id"=>$select["classify_id"]]);
        //$list = $modules->select();
        foreach($list as $val) {
            $func = M("modules_func")->where(["modules_id"=>$val["id"],"status"=>ConstantUtil::GLOBAL_TRUE])->select();
            $val["func_list"] = $func;
            $result[] = $val;
        }

        $this->assign([
            "list"      => $result ,
            "page"      => $show ,
            "classify"  => $classify ,
            "select"    => $select ,
        ]);
        $this->display("modules/index");
    }

    /**
     * 模块添加页
     */
    public function add() {

        $root       = I("post.root");
        $name       = I("post.name");
        $url        = I("post.url");
        $classify   = I("post.classify");
        $data["name"] = $name;
        $data["url"] = $url;
        $data["create_time"] = date("Y-m-d H:i:s");
        $data["classify_id"] = $classify;
        $data["status"] = ConstantUtil::GLOBAL_TRUE;
        if(!empty($root)) {
            $post = I("post.");
            unset($post["root"]);
            $file_result = $this->createFile($post);
            if(empty($file_result)) $this->error("控制器或者视图已经存在");
        }
        $result = M("modules")->add($data);
        if(empty($result)) {
            $this->error("添加失败!");
        } else {
            A("index")->header();
            $this->success("添加成功!");
        }
    }




    /**
     * 编辑视图
     * @param 
     * @return mixed
     */
    public function editorView() {
        $id = I("get.id");
        $list = M("modules")->where(["id"=>$id])->find();
        $classify = D("Classify")->getClassify();
        $this->assign(["classify"=>$classify,"list"=>$list]);
        $this->display("modules/editor");
    }

    /**
     * 模块编辑页面
     */
    public function editor() {

        $id                     = I("post.id");
        $data['name']           = I("post.name");
        $data['url']            = I("post.url");
        $data['classify_id']    = I("post.classify");
        $result = M("modules")->where(["id"=>$id])->save($data);
        if(empty($result)) {
            $this->error("保存失败!");
        } else {
            A("index")->header();
            $this->success("保存成功!");
        }
    }

    /**
     * 模块删除页面
     */
    public function delete() {
        $id     = I("get.id");
        $result = D("modules")->upDelete($id);
        if(empty($result)) {
            $this->error("删除失败!");
        } else {
            A("index")->header();
            $this->success("删除成功!");
        }
    }

    /**
     * 模块添加页面
     */
    public function addView() {

        $classify = D("Classify")->getClassify();
        $this->assign([
            "list"  => $classify ,
            "model" => C('MODULE_ALLOW_LIST'),

        ]);
        $this->display("modules/add");
    }

    /**
     * 动作添加页面
     * @return string
     */
    public function funcAddView() {
        $id = I("get.id");
        if(empty($id)) return '';
        $this->assign("id",$id);
        $this->display("modules/func_add");
    }

    /**
     * 动作添加
     */
    public function funcAdd() {

        $name = I("post.name");
        $url = I("post.url");
        $id = I("post.id");
        $data["name"] = $name;
        $data["url"] = $url;
        $data["create_time"] = date("Y-m-d H:i:s");
        $data["modules_id"] = $id;
        $data["status"] = ConstantUtil::GLOBAL_TRUE;
        $result = M("modules_func")->add($data);
        if(empty($result)) {
            $this->error("添加失败!");
        } else {
            $this->success("添加成功!");
        }
    }

    /**
     * 动作删除
     */
    public function funcDelete() {
        $id = I("get.id");
        if(empty($id)) $this->error("参数有误!");
        $result = M("modules_func")->where(["id"=>$id])->save(["status"=>ConstantUtil::GLOBAL_FALSE]);
        if(empty($result)) {
            $this->error("添加失败!");
        } else {
            $this->success("添加成功!");
        }
    }

    /**
     *  动作编辑页面
     */
    public function funcEditorView() {

        $id = I("get.id");
        $list = M("modules_func")->where(["id"=>$id])->find();
        $this->assign(["id"=>$id,"list"=>$list]);
        $this->display("modules/func_editor");
    }

    /**
     * 动作编辑
     */
    public function funcEditor() {
        $id = I("post.id");
        $name = I("post.name");
        $url = I("post.url");
        $data = [
            "name" => $name,
            "url" => $url
        ];
        $result = M("modules_func")->where(["id"=>$id])->save($data);
        if(empty($result)) {
            $this->error("添加失败!");
        } else {
            $this->success("添加成功!");
        }

    }

    public function urlManage($url) {
        if(!strstr($url,"@")) return false;
        $url = explode("@",$url);
        return $url[0].'/'.$url[1];
    }


    private function createFile($post="") {

        $url    = $post["url"];
        $db     = $post["db"];
        if(empty($url)) return false;
        $url = explode("@",$url);
        $class = $url[0];
        $small_class = strtolower($class);
        $content = '<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Common\ConstantUtil;
use Think\Page;
class '.$class.'Controller extends CommonController {

    public function index() {
        import("ORG.Think.Page");
        $obj =  M("'.$db.'")->order("id desc");
        $obj_list = clone $obj;
        $count  = $obj->count();
        $page   = new Page($count,ConstantUtil::ADMIN_PAGE);
        $show   = $page->show();
        $list   = $obj_list->limit($page->firstRow.",".$page->listRows)->select();
        $this->assign([
            "list"  =>  $list ,
            "class" => "'.$class.'" ,
            "page" => $show ,
        ]);
        $this->display("'.$small_class.'/index");


    }

    public function addView() {
        $this->assign([
            "class" => "'.$class.'" ,
        ]);
        $this->display("'.$small_class.'/add");
    }

    public function add(){
        $data = I("post.");
        $result = M("'.$db.'")->add($data);
        if(empty($result)) {
            $this->error("添加失败!");
        } else {
            $this->success("添加成功!");
        }
    }

    public function info() {
        $id = I("get.id");
        if(empty($id)) $this->error("参数错误!");
        $list = M("'.$db.'")->where(["id"=>$id])->find();
        $this->assign([
            "list"  =>  $list ,
             "class" => "'.$class.'" ,
        ]);
        $this->display("'.$small_class.'/info");
    }

    public function editorView(){
        $id = I("get.id");
        if(empty($id)) $this->error("参数错误!");
        $list = M("'.$db.'")->where(["id"=>$id])->find();
        $this->assign([
            "list"=>$list ,
            "class" => "'.$class.'" ,
        ]);
        $this->display("'.$small_class.'/editor");
    }

    public function editor(){
        $data = I("post.");
        $id = $data["id"];
        unset($data["id"]);
        $result = M("'.$db.'")->where(["id"=>$id])->save($data);
        if(empty($result)) {
            $this->error("保存失败!");
        } else {
            $this->success("保存成功!");
        }
    }
    public function delete(){

        $id = I("get.id");
        if(empty($id)) $this->error("参数错误!");
        $result = M("'.$db.'")->where(["id"=>$id])->delete();
        if(empty($result)) {
            $this->error("删除失败!");
        } else {
            $this->success("删除成功!");
        }
    }
}
';
        $path = __DIR__;
        $view = $path."/../"."View/standard";
        $file = $path."/".$class."Controller.class.php";
        if(is_file($file)) return false;
        $file = fopen($file, "w");
        if(empty($file)) return false;
        fwrite($file, $content);
        fclose($file);
        if(is_dir($path."/../"."View/".strtolower($class)."")) return false;
        $xCopy = $this->xCopy($view,$path."/../"."View/".strtolower($class)."");
        if(empty($xCopy)) return false;
        return true;
    }

    /**
     * @param string $source            源目录名
     * @param string $destination       目的目录名
     * @param string $child             复制时，是不是包含的子目录
     * @return int
     */
    private  function xCopy($source="", $destination="", $child=""){
        if(!is_dir($source)){
            return false;
        }
        if(!is_dir($destination)){
            mkdir($destination,0777);
        }
        $handle=dir($source);
        while($entry=$handle->read()) {
            if(($entry!=".")&&($entry!="..")){
                if(is_dir($source."/".$entry)){
                    if($child)
                        $this->xCopy($source."/".$entry,$destination."/".$entry,$child);
                }
                else{
                    copy($source."/".$entry,$destination."/".$entry);
                }
            }
        }
        return true;
    }




}